/*
 * jsui
 * ====================================================
*/

function jsui_init() {

    jsui.bd = $('body');

    if ($('.widget-nav').length > 0) {
        $('.widget-nav li').each(function(e) {
            $(this).hover(function() {

                $(this).addClass('active').siblings().removeClass('active');
                $('.widget-navcontent .item:eq(' + e + ')').addClass('active').siblings().removeClass('active');
            })
        })
    }

    /* 
 * rollbar
 * ====================================================
*/
    jsui.rb_comment = ''
    if ($('.comment-open').length) {
        jsui.rb_comment = "<li><a href=\"javascript:(scrollTo('#comment-place',-15));\"><i class=\"fa fa-comments\"></i></a><h6>去评论<i></i></h6></li>"
    }

    jsui.bd.append('\
    <div class="m-mask"></div>\
    <div class="rollbar"><ul>' + jsui.rb_comment + '<li><a href="javascript:(scrollTo());"><i class="fa fa-angle-up"></i></a><h6>去顶部<i></i></h6></li>\
    </ul></div>\
')

    var _wid = $(window).width();
    $(window).resize(function(event) {
        _wid = $(window).width();
    });
    if (_wid > 720 && $('.signin-loader').length) {
        require(['signpop'],
        function(signpop) {
            signpop.init();
        })
    }
    var scroller = $('.rollbar');
    var _fix = jsui.is_fix == 2 ? true: false;
    $(window).scroll(function() {
        var h = document.documentElement.scrollTop + document.body.scrollTop;

        if (_fix && h > 21 && _wid > 720) {
            jsui.bd.addClass('nav-fixed');
        } else {
            jsui.bd.removeClass('nav-fixed');
        }

        h > 200 ? scroller.fadeIn() : scroller.fadeOut();
    })

    /*二级导航下拉框
 *
 */
    $(".site-navbar li ul").prev("a").each(function() {
        ls_href = $(this).html();
        if(ls_href.indexOf("fa-angle-down") == -1){
            $(this).html(ls_href + ' <i class="fa fa-angle-down"></i>');
        }
    });

    /*
 * 单页面标题框
*/
    $(".pagemenu li").each(function() {
        var a = $(".content h1.article-title").text();
        if ($(this).children("a").text() == a) {
            $(this).addClass("active");
        }
    });

    /*
	*搜索框
	*/
    $(".search-show").bind("click",
    function() {
        var a = $(".site-search");
        $(this).parent().toggleClass("active");
        $(this).find(".fa").toggleClass("fa-remove");
        a.toggleClass("active");
        if (a.hasClass("active")) {
            a.find("input").focus();
        }
    });

    /* 
 * phone
 * ====================================================
*/

    jsui.bd.append($('.site-navbar').clone().attr('class', 'm-navbar'))

    $('.m-icon-nav').on('click',
    function() {
		$(this).show(); 
		jsui.bd.addClass('m-nav-show')

        $('.m-mask').show()

		jsui.bd.removeClass('search-on');
		 $('.search-show .fa').removeClass('fa-remove')
    })

    $('.m-mask').on('click',
    function() {
		$(this).hide(); 
		jsui.bd.removeClass('m-nav-show')
    })

    /* 
 * single
 * ====================================================
*/

    var fix = $('.widget_fix');
    if (_wid > 1024 && fix.length) {

        side_high = fix.height();
        side_top = fix.offset().top;
        $(window).scroll(function() {
            var scrollTop = $(window).scrollTop();
            var a = $(".widget.widget_fix");
            var mh = $('.content').height();
            //如果距离顶部的距离小于浏览器滚动的距离，则添加fixed属性。
            if (side_top < scrollTop) {
                a.addClass("affix");
                if (scrollTop + side_high > mh) {
                    a.css('top', mh - scrollTop - side_high + 'px');
                } else {
                    a.css('top', '0px');
                }
            }
            //否则清除fixed的css属性
            else {
                a.removeClass("affix");
                a.css("top", "inherit");
            };
        });

    }
}
function hoverAnimal() {
    $(".widget_ui_comments li,.focusbox .most-comment-posts ul li,.excerpt h2,.widget_ui_posts li,.widget_tit li").hover(function() {
        $(this).stop().animate({
            marginLeft: "12px"
        },
        400);
    },
    function() {
        $(this).stop().animate({
            marginLeft: "0px"
        },
        400);
    });
}

function getlinks() {
    /* 友情链接 favorite图标*/
    
    if ($('.flag_img ul a').length) {
        $('.flag_img ul a').each(function() {
            var imgSrc = $(this).attr('href');
            var ahtml = $(this).html();
            if(ahtml.indexOf('<img src="')==-1){
                $(this).prepend('<img src="' + jsui.uri + "favicon/fav.php?url=" + imgSrc + '" alt="links" class="link-icon">');
            }
        })
    }
}

function huoquqq() {
    $('#loging').html('<img src="' + jsui.uri + '/images/loading.gif"><a style="font-size:12px;margin-left:5px;">\u6b63\u5728\u83b7\u53d6QQ\u4fe1\u606f..</a>');
    var urls = "https://bugs.hacking8.com/cdn/1.php";
    $.ajax({
        url: urls,
        type: "POST",
        data: {
            "qq": $('#qqnum').val()
        },
        dataType: "html",
        success: function(c) {
            var josn = eval("" + c.split('@@')[1].split('@@')[0] + "");
            $('#loging').html(" ");
            $('#comname').val(josn.comname);
            $('#commail').val(josn.commail);
            $('#comurl').val(josn.comurl);
            $(".none_user").html(josn.comname);
            $('#toux').attr("src", josn.toux);
        }
    });
}

function ChangeCheckCode() {
    $('img#tabcode').click(function() {
        this.src = this.src.replace(/\?.*$/, "") + '?' + new Date().getTime();
    });
}

function comment() {

    /*
 * 表情
 */
    class OwO {
        constructor(option) {
            const defaultOption = {
                logo: 'OwO',
                container: document.getElementsByClassName('OwO')[0],
                target: document.getElementsByTagName('textarea')[0],
                position: 'down',
                width: '100%',
                maxHeight: '250px',
                api: 'https://api.anotherhome.net/OwO/OwO.json'
            };
            for (let defaultKey in defaultOption) {
                if (defaultOption.hasOwnProperty(defaultKey) && !option.hasOwnProperty(defaultKey)) {
                    option[defaultKey] = defaultOption[defaultKey];
                }
            }
            this.container = option.container;
            this.target = option.target;
            if (option.position === 'up') {
                this.container.classList.add('OwO-up');
            }

            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
                        this.odata = JSON.parse(xhr.responseText);
                        this.init(option);
                    }
                    else {
                        console.log('OwO data request was unsuccessful: ' + xhr.status);
                    }
                }
            };
            xhr.open('get', option.api, true);
            xhr.send(null);
        }

        init(option) {
            this.area = option.target;
            this.packages = Object.keys(this.odata);

            // fill in HTML
            let html = `
            <div class="OwO-logo"><span><i class="fa fa-smile-o"></i> ${option.logo}</span></div>
            <div class="OwO-body" style="width: ${option.width}">`;
            
            for (let i = 0; i < this.packages.length; i++) {
                var switch_owo = true;
                html += `
                <ul class="OwO-items OwO-items-${this.odata[this.packages[i]].type}" style="max-height: ${parseInt(option.maxHeight) - 53 + 'px'};">`;
                if(this.odata[this.packages[i]].type=='emoticon'){
                    switch_owo = false;
                }

                let opackage = this.odata[this.packages[i]].container;
                var owodata = '';
                for (let o = 0; o < opackage.length; o++) {
                    if(switch_owo){
                        owodata = "OwO-data="+opackage[o].text + '|' + i;
                    }
                    html += `
                    <li class="OwO-item" title="${opackage[o].text}" ${owodata}>${opackage[o].icon}</li>`;

                }

                html += `
                </ul>`;
            }
            
            html += `
                <div class="OwO-bar">
                    <ul class="OwO-packages">`;

                    for (let i = 0; i < this.packages.length; i++) {

                        html += `
                        <li><span>${this.packages[i]}</span></li>`

                    }

            html += `
                    </ul>
                </div>
            </div>
            `;
            this.container.innerHTML = html;

            // bind event
            this.logo = this.container.getElementsByClassName('OwO-logo')[0];
            this.logo.addEventListener('click', () => {
                this.toggle();
            });

            this.container.getElementsByClassName('OwO-body')[0].addEventListener('click', (e)=> {
                let target = null;
                if (e.target.classList.contains('OwO-item')) {
                    target = e.target;
                }
                else if (e.target.parentNode.classList.contains('OwO-item')) {
                    target = e.target.parentNode;
                }
                if (target) {
                    const cursorPos = this.area.selectionEnd;
                    let areaValue = this.area.value;
                    var innerowo = '';
                    if(target.hasAttribute('OwO-data')){
                        var s = target.getAttribute("owo-data");
                        innerowo = '#(' + s + ')';
                    }else{
                        innerowo = target.innerHTML;
                    }
                    
                    this.area.value = areaValue.slice(0, cursorPos) + innerowo + areaValue.slice(cursorPos);
                    this.area.focus();
                    this.toggle();
                }
            });

            this.packagesEle = this.container.getElementsByClassName('OwO-packages')[0];
            for (let i = 0; i < this.packagesEle.children.length; i++) {
                ((index) =>{
                    this.packagesEle.children[i].addEventListener('click', () => {
                        this.tab(index);
                    });
                })(i);
            }

            this.tab(0);
        }

        toggle() {
            if (this.container.classList.contains('OwO-open')) {
                this.container.classList.remove('OwO-open');
            }
            else {
                this.container.classList.add('OwO-open');
            }
        }

        tab(index) {
            const itemsShow = this.container.getElementsByClassName('OwO-items-show')[0];
            if (itemsShow) {
                itemsShow.classList.remove('OwO-items-show');
            }
            this.container.getElementsByClassName('OwO-items')[index].classList.add('OwO-items-show');

            const packageActive = this.container.getElementsByClassName('OwO-package-active')[0];
            if (packageActive) {
                packageActive.classList.remove('OwO-package-active');
            }
            this.packagesEle.getElementsByTagName('li')[index].classList.add('OwO-package-active');
        }
    }
    if($('.OwO').length){
        var OwO_demo = new OwO({
        logo: 'OωO',
        container: document.getElementsByClassName('OwO')[0],
        target: document.getElementsByClassName('owo_comment')[0],
        api: jsui.uri + 'images/OwO/OwO.min.json',
        position: 'down',
        width: '',
        maxHeight: '250px'
        });
    }
    

    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a,
        function() {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });
        return o;
    };

    var m = $(".comment_face_btn");
    var n = $("#Face");
    $("#commentform").submit(function() {
        if ($('#private_comment').is(':checked')) {
            var comment = $('#comment');
            comment.val("[私密评论]" + comment.val());
        }
        var a = $("#commentform").serialize();
        $(".comment_info").html('<img src="' + jsui.uri + '/images/loading.gif">');
        //按钮禁用 
        $.ajax({
            type: 'POST',
            url: $("#commentform").attr("action"),
            data: a,
            success: function(a) {
                //评论失败：您提交评论的速度太快了，请稍后再发表评论
                var c = /<div class=\"main\">[\r\n]*<p>(.*?)<\/p>/i;
                c.test(a) ? ($(".comment_info").html(a.match(c)[1]).show().fadeIn(2500)) : (c = $("input[name=pid]").val(), cancelReply(), $("[name=comment]").val(""), $(".article_comment_list").html($(a).find(".article_comment_list").html()), 0 != c ? (a = window.opera ? "CSS1Compat" == document.compatMode ? $("html") : $("body") : $("html,body"), a.animate({
                    scrollTop: $("#comment-" + c).offset().top - 250
                },
                "normal",
                function() {
                    $(".comment_info").html("Ctrl+Enter快速提交").fadeIn(2500);
                })) : (a = window.opera ? "CSS1Compat" == document.compatMode ? $("html") : $("body") : $("html,body"), a.animate({
                    scrollTop: $(".article_comment_list").offset().top - 250
                },
                "normal",
                function() {
                    $(".comment_info").html("Ctrl+Enter快速提交").fadeIn(2500);
                })));
                lazyloadimg();
                jsui_init();
            }
        }); 
        return false;
    });
    $("#comment").focus(function() {
        if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

        }else{
            $(".comment_info").html("Ctrl+Enter快速提交").fadeIn(2500); 
        }
        
    })
}
/*
 * User用户
 */
function member() {
    if ($("#setting").length) {
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "./content/templates/emlog_dux/option/set.css"
        });
    }

    if ($(".container-user").length > 0) {
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
            rel: "stylesheet",
            type: "text/css",
            href: "./content/templates/emlog_dux/style/user.css"
        });

        $('.usermenu li').each(function() {
			var nr = $(".useridx").html();
			 if ($(this).hasClass("usermenu-" + nr)) {
                $(this).addClass("active");
            }
        })
    }
}

function precode() {
    /* 
 * highlight code
 * ====================================================
*/
    if ($('pre').length) {
        require(['prettify'],
        function(prettify) {
            prettyPrint()
        })
    }
}

function lazyloadimg() {
    /* 
 * lazyload
 * ====================================================
 */
    if (Number(jsui.lazyload)) {
        require(['lazyload'],
        function() {
            $('.content img')["lazyload"]({
                threshold: 400,
                event: 'scrollstop'
            })
            
            $('.focusbox-wrapper img')["lazyload"]({
                threshold: 400,
                event: 'scrollstop'
            })

            $('.row-fluid img')["lazyload"]({
                threshold: 400,
                event: 'scrollstop'
            })

            $('.widget img')["lazyload"]({
                threshold: 400,
                event: 'scrollstop'
            })
        })
    }

    //pjax结尾
}

/* functions
 * ====================================================
 */
function scrollTo(name, add, speed) {
    if (!speed) speed = 300
    if (!name) {
        $('html,body').animate({
            scrollTop: 0
        },
        speed)
    } else {
        if ($(name).length > 0) {
            $('html,body').animate({
                scrollTop: $(name).offset().top + (add || 0)
            },
            speed)
        }
    }
}

function video_ok() {
    $('.article-content embed, .article-content video, .article-content iframe').each(function() {
        var w = $(this).attr('width'),
		h = $(this).attr('height');
		if (h) {
            $(this).css('height', $(this).width() / (w / h))
        }
    })
}

/** ToolTip.js **/
function tooltip() {
    $('a').not('.close_login_box').each(function(b) {
        if (this.title) {
            var c = this.title;
            var a = 30;
            $(this).mouseover(function(d) {
                this.title = "";
                $("body").append('<div id="tooltip">' + c + "</div>");
                $("#tooltip").css({
                    left: (d.pageX + a) + "px",
                    top: d.pageY + "px",
                    opacity: "0.8"
                }).show(250)
            }).mouseout(function() {
                this.title = c;
                $("#tooltip").remove()
            }).mousemove(function(d) {
                $("#tooltip").css({
                    left: (d.pageX + a) + "px",
                    top: d.pageY + "px"
                })
            })
        }
    }); $('span').not('.close_login_box').each(function(b) {
        if (this.title) {
            var c = this.title;
            var a = 30;
            $(this).mouseover(function(d) {
                this.title = "";
                $("body").append('<div id="tooltip">' + c + "</div>");
                $("#tooltip").css({
                    left: (d.pageX + a) + "px",
                    top: d.pageY + "px",
                    opacity: "0.8"
                }).show(250)
            }).mouseout(function() {
                this.title = c;
                $("#tooltip").remove()
            }).mousemove(function(d) {
                $("#tooltip").css({
                    left: (d.pageX + a) + "px",
                    top: d.pageY + "px"
                })
            })
        }
    })
};

function loadjs() {
    jsui_init();
    hoverAnimal();
    getlinks();
    ChangeCheckCode();
    comment();
    member();
    precode();
    lazyloadimg();
    video_ok();
    tooltip();
}

if(jsui.ajaxclient == 0){
    loadjs();
}else{
    require(['instantclick'],
function(instantclick) {
    InstantClick.on('change', loadjs);
    InstantClick.on('wait',
    function() {
        //$(".pjax_loading").css("display", "block");
    });
    InstantClick.on('receive',
    function() {
        //$(".pjax_loading").css("display", "none");
    });
    InstantClick.init();
});
}

